from django.urls import re_path
from stark.service.s1 import StarkHandler
from app_main.forms.for_stark import ScoreRecordModelForm
from app_main import models


class ScoreRecordHandler(StarkHandler):
    list_display = ['content', 'score_change', 'user']
    model_form_class = ScoreRecordModelForm

    def get_urls(self):
        patterns = [
            re_path('list/(?P<sid>\d+)/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            re_path('add/(?P<sid>\d+)/$', self.wrapper(self.add_view), name=self.get_add_url_name)
        ]

        patterns.extend(self.extra_urls())

        return patterns

    def get_query_set(self, request, *args, **kwargs):
        s_id = kwargs.get('sid')
        first_q_set = self.model_class.objects.filter(student_id=s_id)
        return first_q_set

    def save(self, request, form_obj, is_update, *args, **kwargs):
        s_id = kwargs.get('sid')
        current_user_id = request.session['user_info']['id']

        form_obj.instance.student_id = s_id
        form_obj.instance.user_id = current_user_id
        form_obj.save()

        # 更改学生的 score
        s_obj = models.Student.objects.filter(id=s_id).first()
        score = form_obj.instance.score_change
        s_obj.score += score
        s_obj.save()
